
import CONFIG from './config.js';



const request = (api = '', options = {}) => {
	
	// 用户登录token
	const token = uni.getStorageSync('yeyuMini_token');
	
	const {
		method = 'POST',
		headerToken = token,
		apiServer = CONFIG.API_SERVER,
		params = {},
		success = () => {},
		fail = () => {},
		complete = () => {},
		...others
	} = options;
	
	const url = CONFIG.API_DOMAIN + '/' + apiServer + api;
	
	return uni.request({
		...others,
		url,
		method,
		header: {
			'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
			'headerToken': headerToken || token,
			"osType": 'JS',
		},
		data: params,
		success: res => {
			const data = res.data;
			
			if (res.statusCode !== 200) {
				uni.showToast({
					icon: 'none',
					title: '未知错误',
					mask: true,
				});
				return;
			}
			
				// 成功的回调
			if (data.code === 0) {
				success(data);
				return;
			}
			
			// code === -4 代表登录过期或失效，需要重新登录
			if (data.code === -4) {
				const msg = data.msg || '登录失效，请重新登录';
				uni.removeStorageSync('yeyuMini_token');
				uni.removeStorageSync('yeyuMini_userInfo');
				uni.showToast({
					title: msg,
					icon: 'none',
					success: function () {
						setTimeout(() => {
							uni.reLaunch({
								url: `/pages/index/index?redirect=/login`,
							})
						}, 1500);
					},
				});
				return;
			}
			
			uni.showToast({
				icon: 'none',
				title: data.msg || '未知错误',
				mask: true,
			});
			fail();

		},
		fail: (res = {}) => {
			uni.showToast({
				icon: 'none',
				title: '未知错误',
				mask: true,
			});
			
			// 错误的回调
			fail();
		},
		complete: () => {
			complete();
		}
	});
}

export default request;
